<script setup lang="ts">
import { computed, onMounted, ref } from 'vue';

import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

import PetSelector from '../components/PetSelector.vue';
import ServiceItemModal from './components/ServiceItemModal.vue';

// 响应式数据
const selectedPet = ref<any>(null);
const selectedOrder = ref<any>(null);
const activeTab = ref('today');
const searchKeyword = ref('');
const showServiceModal = ref(false);

// 模拟数据
const pets = ref([
  {
    id: '1',
    name: '球球',
    ownerName: '赵女士',
    ownerPhone: '183',
    type: '狗',
    breed: '金毛',
    gender: '公',
    age: '3岁',
    neutered: '已绝育',
    doctor: '周院长',
    phone: '183',
  },
  {
    id: '2',
    name: '兜兜',
    ownerName: '王先生',
    ownerPhone: '18243535',
    type: '猫',
    breed: '英短',
    gender: '母',
    age: '2岁',
    neutered: '未绝育',
    doctor: '孙医生',
    phone: '18243535',
  },
  {
    id: '3',
    name: '球球',
    ownerName: '赵女士',
    ownerPhone: '183',
    type: '狗',
    breed: '拉布拉多',
    gender: '公',
    age: '1岁',
    neutered: '未绝育',
    doctor: '孙医生',
    phone: '183',
  },
]);

const groomingOrders = ref<any[]>([]);

// 服务项目表格列定义
const serviceColumns = [
  { title: '名称', dataIndex: 'name', key: 'name', width: 200 },
  { title: '类别', dataIndex: 'category', key: 'category', width: 100 },
  { title: '单价', dataIndex: 'price', key: 'price', width: 100 },
  { title: '数量', dataIndex: 'quantity', key: 'quantity', width: 80 },
  { title: '总价(元)', dataIndex: 'totalPrice', key: 'totalPrice', width: 120 },
  { title: '付款状态', dataIndex: 'status', key: 'status', width: 100 },
  { title: '操作', key: 'action', width: 80 },
];

// 计算属性 - 保留用于其他功能
const filteredPets = computed(() => {
  if (!searchKeyword.value) {
    return pets.value;
  }
  return pets.value.filter(
    (pet) =>
      pet.name.includes(searchKeyword.value) ||
      pet.ownerName.includes(searchKeyword.value) ||
      pet.ownerPhone.includes(searchKeyword.value),
  );
});

const totalAmount = computed(() => {
  if (!selectedOrder.value?.serviceItems) return 0;
  return selectedOrder.value.serviceItems.reduce((sum: number, item: any) => {
    return sum + (item.price || item.unitPrice || 0) * (item.quantity || 1);
  }, 0);
});

// 方法
const selectPet = (pet: any) => {
  selectedPet.value = pet;
  selectedOrder.value = null;
  loadGroomingOrders(pet.id);
};

const closePetTab = () => {
  selectedPet.value = null;
  selectedOrder.value = null;
  groomingOrders.value = [];
};

const loadGroomingOrders = (petId: string) => {
  // 模拟加载美容服务单
  groomingOrders.value = [
    {
      id: '1',
      orderName: '美容单1',
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      status: 'pending',
      serviceStaff: '曾前台',
      salesStaff: '曾前台',
      remarks: '',
      serviceItems: [],
    },
  ];

  // 默认选择最新的美容服务单
  if (groomingOrders.value.length > 0) {
    selectOrder(groomingOrders.value[0]);
  }
};

const createNewOrder = () => {
  const newOrder = {
    id: Date.now().toString(),
    orderName: `美容单${groomingOrders.value.length + 1}`,
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    status: 'pending',
    serviceStaff: '曾前台',
    salesStaff: '曾前台',
    remarks: '',
    serviceItems: [],
  };

  groomingOrders.value.unshift(newOrder);
  selectOrder(newOrder);
  message.success('新建美容服务单成功！');
};

const selectOrder = (order: any) => {
  selectedOrder.value = order;
};

const printOrder = () => {
  message.info('打印功能开发中...');
};

const saveOrder = () => {
  if (!selectedOrder.value) return;

  // 保存到本地存储
  const key = `grooming_orders_${selectedPet.value.id}`;
  localStorage.setItem(key, JSON.stringify(groomingOrders.value));

  message.success('美容服务单保存成功！');
};

const searchPets = () => {
  // 搜索功能已通过计算属性实现
};

const handleServiceItemSuccess = (serviceItems: any[]) => {
  if (!selectedOrder.value) return;

  // 添加多个服务项目
  serviceItems.forEach((serviceItem) => {
    selectedOrder.value.serviceItems.push({
      ...serviceItem,
      id: Date.now().toString() + Math.random().toString(36).slice(2, 11),
    });
  });

  showServiceModal.value = false;
  message.success(`成功添加 ${serviceItems.length} 个服务项目！`);
};

const removeServiceItem = (item: any) => {
  if (!selectedOrder.value) return;

  const index = selectedOrder.value.serviceItems.findIndex(
    (i: any) => i.id === item.id,
  );
  if (index !== -1) {
    selectedOrder.value.serviceItems.splice(index, 1);
    message.success('服务项目删除成功！');
  }
};

// 生命周期
onMounted(() => {
  // 初始化数据
  // 默认选择第一个宠物
  if (pets.value.length > 0 && !selectedPet.value) {
    selectPet(pets.value[0]);
  }
});
</script>

<template>
  <div class="grooming-container">
    <!-- 左侧：宠物信息和美容服务单列表 -->
    <div class="left-panel">
      <!-- 宠物信息 -->
      <div v-if="selectedPet" class="pet-info-section">
        <div class="pet-tab">
          <span class="pet-name"
            >{{ selectedPet.name }}({{ selectedPet.ownerName }})</span
          >
          <a-button type="text" size="small" @click="closePetTab">×</a-button>
        </div>

        <div class="pet-details">
          <div class="detail-row">
            <span class="label">主人：</span>
            <span class="value">{{ selectedPet.ownerName }}</span>
          </div>
          <div class="detail-row">
            <span class="label">电话：</span>
            <span class="value">{{ selectedPet.ownerPhone }}</span>
          </div>
          <div class="detail-row">
            <span class="label">种类：</span>
            <span class="value">{{ selectedPet.type }}</span>
          </div>
          <div class="detail-row">
            <span class="label">品种：</span>
            <span class="value">{{ selectedPet.breed || '未知' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">性别：</span>
            <span class="value">{{ selectedPet.gender || '未知' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">年龄：</span>
            <span class="value">{{ selectedPet.age || '未知' }}</span>
          </div>
          <div class="detail-row">
            <span class="label">绝育：</span>
            <span class="value">{{ selectedPet.neutered || '未知' }}</span>
          </div>
        </div>
      </div>

      <!-- 美容服务单列表 -->
      <div v-if="selectedPet" class="grooming-orders-section">
        <h3>美容服务单</h3>
        <div class="orders-list">
          <div
            v-for="order in groomingOrders"
            :key="order.id"
            class="order-item"
            :class="{ active: selectedOrder?.id === order.id }"
            @click="selectOrder(order)"
          >
            <div class="order-info">
              <span class="order-name">{{ order.orderName }}</span>
              <span class="order-time">{{ order.createTime }}</span>
            </div>
            <div class="order-status">
              <a-tag :color="order.status === 'pending' ? 'orange' : 'green'">
                {{ order.status === 'pending' ? '待付' : '已付' }}
              </a-tag>
            </div>
          </div>
        </div>

        <a-button
          type="primary"
          block
          @click="createNewOrder"
          class="new-order-btn"
        >
          + 新建美容单
        </a-button>
      </div>
    </div>

    <!-- 右侧：美容服务单表单 -->
    <div class="right-panel">
      <div v-if="selectedOrder" class="grooming-form">
        <!-- 表单头部 -->
        <div class="form-header">
          <div class="header-left">
            <h2>美容单</h2>
            <span class="create-time"
              >创建时间: {{ selectedOrder.createTime }}</span
            >
          </div>
          <div class="header-right">
            <a-button
              type="default"
              @click="printOrder"
              style="margin-right: 8px"
              title="打印"
            >
              🖨️
            </a-button>
            <a-button type="primary" @click="saveOrder">保存</a-button>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="form-section">
          <h3>基本信息</h3>
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="服务人员">
                <a-select
                  v-model:value="selectedOrder.serviceStaff"
                  placeholder="请选择服务人员"
                  style="width: 100%"
                >
                  <a-select-option value="曾前台">曾前台</a-select-option>
                  <a-select-option value="李美容师">李美容师</a-select-option>
                  <a-select-option value="王美容师">王美容师</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="销售人员">
                <a-select
                  v-model:value="selectedOrder.salesStaff"
                  placeholder="请选择销售人员"
                  style="width: 100%"
                >
                  <a-select-option value="曾前台">曾前台</a-select-option>
                  <a-select-option value="张销售">张销售</a-select-option>
                  <a-select-option value="刘销售">刘销售</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item label="备注">
            <a-textarea
              v-model:value="selectedOrder.remarks"
              placeholder="请输入备注信息"
              :rows="3"
            />
          </a-form-item>
        </div>

        <!-- 服务项目 -->
        <div class="form-section">
          <div class="section-header">
            <h3>添加美容服务项目</h3>
            <a-button type="primary" @click="showServiceModal = true">
              + 添加项目
            </a-button>
          </div>

          <div class="service-items">
            <a-table
              :columns="serviceColumns"
              :data-source="selectedOrder.serviceItems"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'price'">
                  ¥{{ (record.price || record.unitPrice || 0).toFixed(2) }}
                </template>
                <template v-else-if="column.key === 'totalPrice'">
                  ¥{{
                    (
                      (record.price || record.unitPrice || 0) *
                      (record.quantity || 1)
                    ).toFixed(2)
                  }}
                </template>
                <template v-else-if="column.key === 'status'">
                  <a-tag color="orange">待付</a-tag>
                </template>
                <template v-else-if="column.key === 'action'">
                  <a-button
                    type="text"
                    size="small"
                    danger
                    @click="removeServiceItem(record)"
                  >
                    🗑️
                  </a-button>
                </template>
              </template>
            </a-table>

            <div class="total-section">
              <span class="total-label">合计：</span>
              <span class="total-amount">¥{{ totalAmount.toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 未选择宠物时的提示 -->
      <div v-else class="no-selection">
        <div class="empty-state">
          <div class="empty-icon">🐕</div>
          <h3>请选择宠物</h3>
          <p>从右侧列表中选择一个宠物来创建美容服务单</p>
        </div>
      </div>
    </div>

    <!-- 右侧：宠物选择面板 -->
    <div class="right-sidebar">
      <PetSelector
        :pets="pets"
        :selected-pet="selectedPet"
        :active-tab="activeTab"
        title="选择宠物"
        @update:selected-pet="selectPet"
        @update:active-tab="activeTab = $event"
        @search="searchPets"
      />
    </div>

    <!-- 添加服务项目模态框 -->
    <ServiceItemModal
      :visible="showServiceModal"
      @update:visible="showServiceModal = $event"
      @success="handleServiceItemSuccess"
    />
  </div>
</template>

<style scoped>
.grooming-container {
  display: flex;
  height: 100vh;
  background-color: #f5f5f5;
}

.left-panel {
  display: flex;
  flex-direction: column;
  width: 300px;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.pet-info-section {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.pet-tab {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  margin-bottom: 16px;
  background: #f0f0f0;
  border-radius: 4px;
}

.pet-name {
  font-weight: bold;
}

.pet-details {
  font-size: 14px;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
}

.label {
  width: 60px;
  color: #666;
}

.value {
  flex: 1;
  color: #333;
}

.grooming-orders-section {
  flex: 1;
  padding: 16px;
}

.grooming-orders-section h3 {
  margin-bottom: 16px;
  color: #333;
}

.orders-list {
  margin-bottom: 16px;
}

.order-item {
  padding: 12px;
  margin-bottom: 8px;
  cursor: pointer;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  transition: all 0.3s;
}

.order-item:hover {
  background: #f6ffed;
  border-color: #1890ff;
}

.order-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.order-info {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.order-name {
  font-weight: bold;
}

.order-time {
  font-size: 12px;
  color: #666;
}

.new-order-btn {
  margin-top: 16px;
}

.right-panel {
  flex: 1;
  margin: 16px;
  overflow: hidden;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 10%);
}

.grooming-form {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.form-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.header-left h2 {
  margin: 0 0 4px;
  color: #333;
}

.create-time {
  font-size: 12px;
  color: #666;
}

.form-section {
  padding: 24px;
  border-bottom: 1px solid #e8e8e8;
}

.form-section h3 {
  margin-bottom: 16px;
  color: #333;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
}

.service-items {
  margin-top: 16px;
}

.total-section {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 16px;
  margin-top: 16px;
  background: #fafafa;
  border-radius: 4px;
}

.total-label {
  margin-right: 8px;
  font-size: 16px;
  font-weight: bold;
}

.total-amount {
  font-size: 20px;
  font-weight: bold;
  color: #1890ff;
}

.form-actions {
  padding: 24px;
  margin-top: auto;
  text-align: right;
}

.no-selection {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.empty-state {
  text-align: center;
}

.empty-icon {
  margin-bottom: 16px;
  font-size: 48px;
}

.empty-state h3 {
  margin-bottom: 8px;
  color: #333;
}

.empty-state p {
  color: #666;
}

.right-sidebar {
  width: 280px;
  background: white;
  border-left: 1px solid #e8e8e8;
}
</style>
